package com.mybatis.plus.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mybatis.plus.entity.UserEntity;
import com.mybatis.plus.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping(value = "/userService")
@RestController
@Slf4j
public class User2Controller {

    @Autowired
    UserService userService;

    @GetMapping(value = "/save")
    public void save(){
        userService.save(new UserEntity("烙铁",22,"河北","乒乓球"));
    }

    @GetMapping(value = "/getOne")
    public void getOne(){
        // 使用lambda方式查询，当查询结果为多个报异常，false为查询其中的第一个
        UserEntity userEntity1 = userService.getOne(Wrappers.<UserEntity>lambdaQuery().eq(UserEntity::getAge,21),false);

        // 使用正常方式查询
        QueryWrapper<UserEntity> wrapper = Wrappers.query();
        wrapper.eq("age",21);
        UserEntity userEntity2 = userService.getOne(wrapper,false);

        log.info(userEntity1.toString());
        log.info(userEntity2.toString());
    }

    /**
     * 自定义扩展service
     */
    @GetMapping(value = "/getName")
    public void getName(){
        // 注解方式：自定义扩展service
        log.info(userService.kuozhan());
        // xml方式： 自定义扩展service
        log.info(userService.kuozhan2());
    }

    /**
     * 分页测试
     */
    @GetMapping(value = "/page")
    public void page(){
        Page<UserEntity> page = new Page<>(2,2);
        IPage<UserEntity> re = userService.pageList(page,Wrappers.<UserEntity>lambdaQuery());
        re.getRecords().stream().forEach(userEntity -> System.out.println(userEntity.getName()));
    }
}
